//
//  UdpManager.m
//  AppFinance
//
//  Created by wei on 12-6-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AFUdpManager.h"

#import "AFSetting.h"
#import "AFMarketNetData.h"

static AFUdpManager *_udpManager = nil;

static int udpType;
static NSString *udpCode;

@implementation AFUdpManager

+(AFUdpManager*) udpManager{
    @synchronized(self){
        if (_udpManager == nil) {
            _udpManager = [[self alloc] init];
            
            [_udpManager udpInit];
        }
    }
    return _udpManager;
}

// UDP 初始化
- (void)udpInit{
    // init udp socket
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    NSError *error = nil;
    if (![udpSocket bindToPort:0 error:&error])
    {
        NSLog(@"Error binding to port: %@", error);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }
    NSLog(@" UDP Manage Socket Ready");
}

// UDP 从后台 进入前台
- (void)appActive{
    if (udpSocket == nil) {
        if (isUdp) {
            NSLog(@" UDP need continue!");
            [self udpStart];
        } else {
            NSLog(@" UDP no need continue!");
        }
    }
}

// UDP 进入后台
- (void)appBackground {
    [self stopTimer];

    NSString *sendTwoString = @"3001";
	NSData *requestData = [sendTwoString dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:requestData toHost:udpHost port:AF_K_MARKET_UDP_PORT withTimeout:-1 tag:0];

    udpSocket = nil;
}

// 初始化udp参数、开始udp监听
// @udpType 0: 只开excode udp, list detail 共用一个 1: listUdp 2:detailUdp
// @udpCode
- (void)initUdpAndStart:(int)_udpType udpCode:(NSString*)_code withHost:host{
    udpType = _udpType;
    udpCode = _code;
    if([host isEqualToString:HTmmarket]){
    udpHost = AF_K_MARKET_UDP_HOST;
    }else if([host isEqualToString:Wenmarket]){
    udpHost = AF_Bika_MARKET_UDP_HOST;
    }
    [self udpStart];
}

// ------------------------------- [S] timer -----------------------------------
- (void)startTimer {
    [self stopTimer];
   	timer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

- (void)stopTimer {
    if (timer != nil) {
        [timer invalidate];
        timer = nil;
    }
}

- (void)onTimer {
    [self udpHeartbeat];
}
// ------------------------------- [E] timer -----------------------------------

// ------------------------------- [S] udp -------------------------------------
- (void)udpStart {
    
    [self udpCommand];
    
    [self startTimer];
}

-(void) udpCommand{
    lastDataUnixTime = [AFUtils localUnixTime];
    
    if (udpSocket == nil) {
        [self udpInit];
    }
    
    isUdp = true;
    NSString *sendTwoString = [NSString stringWithFormat:@"1001,%@",udpCode];
    
    NSData *requestData = [sendTwoString dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:requestData toHost:udpHost port:AF_K_MARKET_UDP_PORT withTimeout:-1 tag:0];
}

- (void)udpHeartbeat {
    [self appActive];

    long long int nowUnixTime = [AFUtils localUnixTime];

    //NSLog(@" lastDataUnixTime = %lld, nowUnixTime = %lld", lastDataUnixTime, nowUnixTime);
    
    // 如果30秒还没有收到 udp 数据，重新发送 请求数据命令
    if((nowUnixTime - lastDataUnixTime) > 20){
        //NSLog(@" no data, send request data command");
        [self udpCommand];
    } else {
        //NSLog(@" udp heart");
        NSString *str = @"2001";
        NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
        [udpSocket sendData:requestData toHost:udpHost port:AF_K_MARKET_UDP_PORT withTimeout:-1 tag:0];
    }
}

- (void)udpEnd {
    [self stopTimer];

    NSString *sendTwoString = @"3001";
    NSData *requestData = [sendTwoString dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:requestData toHost:udpHost port:AF_K_MARKET_UDP_PORT withTimeout:-1 tag:0];

    isUdp = false;
    
    udpSocket = nil;

    NSLog(@"------- udp end --------");
}


#pragma mark - UDP Socket
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address {
    NSLog(@"------- udp didConnectToAddress --------");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error {
    NSLog(@"------- udp didNotConnect --------");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
    //NSLog(@"------- udp didSendDataWithTag --------");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error {
    NSLog(@"------- udp didNotSendDataWithTag --------");
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error {
    NSLog(@" ********** udp udpSocketDidClose ********** ");
    if (isUdp) {
        //isNeedConn = YES;
    }
}

// 异步收到udp
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext {
	
    NSString *udp_str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
//    NSLog(@" ----- udp_str----  %@",udp_str);
    
    //[sock receiveWithTimeout:-1 tag:0];
    
    if ([udp_str isEqualToString:@""]) {

    } else if (isUdp) {
        NSData *jsondata =[udp_str dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        id jsonObject =[NSJSONSerialization   
                        JSONObjectWithData:jsondata //1  
                        options:kNilOptions   
                        error:&error];
        //NSLog(@" ----- jsonObject----  %@",jsonObject);
        if ([jsonObject isKindOfClass:[NSDictionary class]]){
            
            lastDataUnixTime = [AFUtils localUnixTime];
            
            // 获取 udp 数据
            // 0 无缝兼容 list 页面 和 detail 页面,牺牲流量 换 体验
            // 1: listUdp 2:detailUdp
            if (udpType == 0) {
                [[NSNotificationCenter defaultCenter] postNotificationName:K_UDP_MANAGER_NOTIF_LIST object:self userInfo:jsonObject];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_UDP_MANAGER_NOTIF_DETAIL object:self userInfo:jsonObject];
            }
            else if (udpType == 1) {
                [[NSNotificationCenter defaultCenter] postNotificationName:K_UDP_MANAGER_NOTIF_LIST object:self userInfo:jsonObject]; 
            } else if (udpType == 2) {
                [[NSNotificationCenter defaultCenter] postNotificationName:K_UDP_MANAGER_NOTIF_DETAIL object:self userInfo:jsonObject]; 
            }
            
            // 新数据 替换 本地老数据
            [[AFMarketNetData manager] listDataRefershWithUdpData:jsonObject];
            
        } else if ([jsonObject isKindOfClass:[NSArray class]]){
            
        }
    }
}
// ------------------------------- [E] udp -------------------------------------
@end
